using LDNS.Interfaces;
using LDNS.SDK.Commands.Models;

namespace LDNS.Commands
{
    /// <summary>
    /// 重启命令处理器
    /// 处理RESTART命令，重启DNS服务
    /// 作者：huobing
    /// </summary>
    public class RestartCommandHandler : CommandHandlerBase<RestartCommand, DefaultCommandResult>
    {
        private readonly IDnsService _dnsService;
        
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => RestartCommand.NAME;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="dnsService">DNS服务实例</param>
        public RestartCommandHandler(IDnsService dnsService)
        {
            _dnsService = dnsService;
        }
        
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {

                
                // 先停止服务（如果正在运行）
                if (_dnsService.IsRunning)
                {
    
                    // 停止DNS服务，不返回bool值
                    _dnsService.Stop();
                    bool stopped = true;
                    if (!stopped)
                    {
    
                        return CreateErrorResult("停止DNS服务失败，重启过程中断");
                    }
                }
                
                // 等待一小段时间确保服务完全停止
                System.Threading.Thread.Sleep(500);
                
                // 启动服务

                bool started = _dnsService.Start();
                
                if (started)
                {

                    // 启动DNS服务（注意：已在前面启动）
                    return CreateSuccessResult("重启服务成功");
                }
                else
                {

                    return CreateErrorResult("启动服务失败");
                }
            }
            catch (System.Exception ex)
            {

                return CreateErrorResult($"重启服务失败: {ex.Message}");
            }
        }
    }
}